package com.YOUtils.Base;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Created on 2023/6/25
 *
 * @Time 15:42
 * @Program YOUilt
 * @Author YoHaNe/XiaoShuai
 */
public class HttpUtils {

    public static String doGet(String url){
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL u = new URL(url);
            connection = (HttpURLConnection) u.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept","*/*");
            connection.setRequestProperty("Connection","keep-alive");
            connection.connect();
            if(connection.getResponseCode() == 200){
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                StringBuilder sb = new StringBuilder();
                String temp;
                while ((temp = br.readLine()) != null) sb.append(temp);
                result = sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
            result = "Http connection error";
        }
        finally {
            try {
                if(br != null)
                    br.close();
                if(is != null)
                    is.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return result;
    }

}
